package com.szrt.java.day20170113.ch10.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class StudentDaoProxy implements InvocationHandler{

	 private Object obj;

	public StudentDaoProxy(Object obj) {
		this.obj = obj;
	} 
	
	/**
	 *  当我们调用getProxyInstance 方法的时候。因为我们这个类实现InvocationHandler
	 *  
	 *  ==> 结论：jvm会自动会掉invoke
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Object getProxyInstance(){
		
		ClassLoader loader = obj.getClass().getClassLoader();
		Class[] interfaces = obj.getClass().getInterfaces();
		Object object =Proxy.newProxyInstance(loader, interfaces, this);
		
		return object;
	}

	/**
	 * 一统江山
	 */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("在方法执行之前开启事务...");
		Object jieguo = method.invoke(obj, args);
		System.out.println("在方法执行之后提交事务...");
		return jieguo;
	}

}
